<?php 
	namespace Home\Controller;
	use Think\Controller;

	Class BookrdController extends Controller
	{
		public function index()
		{
			$showapi_appid = '27066'; 
		    $showapi_secret = '9e0f60470f5b4078bf41b118e7da7a7c'; 
		    $paramArr = array(
	         'showapi_appid'=> $showapi_appid,
	         'bookId'=> I('bookid'),
	         'cid'=> I('cid')
	         //添加其他参数
   			 );

		    $param = $this->createParam($paramArr,$showapi_secret);
		    // 查询章节
		    $urlBook = 'http://route.showapi.com/211-1?'.$param;
		    $obj = file_get_contents($urlBook);
		    $obj = json_decode($obj);
		    $book = $obj->showapi_res_body->book;

		    // 小说类型
		    $typeName = $book->typeName;
		    // 小说作者
		    $author = $book->author;
		    // 小说书名
		    $name =explode(' ',$book->name)['0'];
		    // 小说的全部章节
		    $chapterList = $book->chapterList;

		    $array = array();
		    foreach ($chapterList as $key=>$value) {
		    	$array[] = $value;

		    	if(I('cid') == $value->cid){
					$currentKey = $key;
		    		
		    		$bookName = $value->name;
		    	}
		    }

		    // echo "<pre>";
		    // var_dump($currentKey);
		    // var_dump($bookName);

		    // echo "啦啦啦啦";
			// 上一章
			$up = $currentKey-1;
			// echo $up;
			// var_dump($array[$up]);	
			$last =  $array[$up]; 

			// 上一章
			$down = $currentKey+1;
			$next = $array[$down];
			// var_dump($next);
		    // exit;

		    // 查询文章内容
		    $url = 'http://route.showapi.com/211-4?'.$param; 
		    $result = file_get_contents($url);
		    $result = json_decode($result);

		    $txt = $result->showapi_res_body->txt;

		    // 小说的bookid
		    $this->assign('bookid',I('bookid'));
		    // 小说的类型
		    $this->assign('typeName',$typeName);
		    // 小说的作者
		    $this->assign('author',$author);
		    // 小说的书名
		    $this->assign('name',$name);
		    // 小说的章节
		    $this->assign('bookName',$bookName);
		    // 小说的内容
		    $this->assign('txt',$txt);
		    // 返回的是上一章的obj数组
		    $this->assign('last',$last);
		    // 返回的是下一章的obj数组
		    $this->assign('next',$next);
			$this->display();
		}

		//创建参数(包括签名的处理)
	    public function createParam ($paramArr,$showapi_secret) {
	         $paraStr = "";
	         $signStr = "";
	         ksort($paramArr);
	         foreach ($paramArr as $key => $val) {
	             if ($key != '' && $val != '') {
	                 $signStr .= $key.$val;
	                 $paraStr .= $key.'='.urlencode($val).'&';
	             }
	         }
	         $signStr .= $showapi_secret;//排好序的参数加上secret,进行md5
	         $sign = strtolower(md5($signStr));
	         $paraStr .= 'showapi_sign='.$sign;//将md5后的值作为参数,便于服务器的效验
	        
	         return $paraStr;
	   }
	} 